

var startButton = document.querySelector(".startButton")
var electButton = document.querySelectorAll(".questionAnswer ul li")
var text = document.querySelectorAll(".questionAnswer ul li .text")
var nextSong = document.querySelector(".questionAnswer .next")
var timeTip = document.querySelector(".timeTip")
var resetButton  = document.querySelector(".challenge-left")
var shareButton = document.querySelector(".challenge-right")


console.log(timeTip);

var timeGoal = 0;
var musicData;
var questionNum = 0;//当前问题数
var sorce = 0;
var audio = document.querySelector(".musicPlay audio")
var antiShake = true;
/*ajax请求数据*/
function $ajax({ method = "GET", url }) {
    return new Promise(function (resolve, reject) {
        // 确定何时成功 何时失败
        let xhr = new XMLHttpRequest();
        xhr.open(method, url);
        xhr.addEventListener("readystatechange", () => {
            if (xhr.readyState !== 4) {
                // 如果 状态值 尚未变成4(未完成),则直接退出函数
                return
            }
            // 如果请求成功,则 调用 resolve
            if (xhr.status == 200) {
                // 将响应体 通过 resolve 传递出去
                resolve(JSON.parse(xhr.response));
            } else {
                let errInfo = {
                    msg: "请求失败",
                    errUrl: url,
                    status: xhr.status
                }
                reject(errInfo)
            }
        });
        xhr.send();
    })
};


//下一首歌切换
nextSong.addEventListener("click", function () {
    if (!antiShake) {
        timeTip.classList.add("timeOver")
        console.log("太快了兄弟");     
        return;
    }
    antiShake = false;
    setTimeout(()=>{
        antiShake = true;
        timeTip.classList.remove("timeOver")
    },2000)
    questionNum++
    text = document.querySelectorAll(".questionAnswer ul li .text")
    for (let i = 0; i < text.length; i++) {
        text[i].innerText = `${musicData[questionNum].item[i]}`
    }
    audio.src = musicData[questionNum].audio;
    audio.play();
})

//选择按钮
electButton.forEach(function (el, idx) {
    el.addEventListener("click", () => {
        /*计算分数 ++先后顺序*/
        if (!antiShake) {
            timeTip.classList.add("timeOver")
            console.log("太快了兄弟");     
            return;
        }
        antiShake = false;
        setTimeout(()=>{
            antiShake = true;
            timeTip.classList.remove("timeOver")
        },2000)
        sorce = (idx == musicData[questionNum].answer) ? ++sorce : sorce;
        console.log(sorce);
        questionNum++;
        //播放
        audio.src = musicData[questionNum].audio;
        audio.play();

        text = document.querySelectorAll(".questionAnswer ul li .text")
        for (let i = 0; i < text.length; i++) {
            text[i].innerText = `${musicData[questionNum].item[i]}`
        }
    })
})

//开始按钮
startButton.addEventListener("click",doing)
function doing() {
    let first = document.querySelector(".first");
    let questionAnswer = document.querySelector(".questionAnswer");
    let swiper = document.querySelector(".swiper-container")
    //播放

    var mySwiper = new Swiper('.swiper-container', {
        direction: 'horizontal', // 垂直切换选项
        loop: false, // 循环模式选项
        autoplay: {
            delay: 10000,
            stopOnLastSlide: false,
            disableOnInteraction: true,
        },
        observer: true,
        noSwiping: true,   //禁止滑动
        on: {
            init: function () {
                swiperAnimateCache(this); //隐藏动画元素 
                swiperAnimate(this); //初始化完成开始动画
            },
            slideChangeTransitionEnd: function () {
                swiperAnimate(this); //每个slide切换结束时也运行当前slide动画
                //this.slides.eq(this.activeIndex).find('.ani').removeClass('ani'); 动画只展现一次，去除ani类名
            }
        },
    })
    audio.src = musicData[questionNum].audio;
    audio.play();
    antiShake = false;
    swiper.style.display ="block"
    setTimeout(()=>{
        antiShake = true;
    },2000)
    console.log(questionAnswer);

    questionAnswer.style.display = "block"
    first.style.transform = "translate(-200vw)"
   
    clock(1000);
    function clock(time) {
        timeGoal = Date.now() + time;
        console.log("进入");
        var timer1 = setInterval(() => {
            let nowTime = Date.now();
            let error = timeGoal - Date.now();

            if (error < 0) {
                var guess = document.querySelector(".good-text")
                var gradingImag = document.querySelector(".grading img")
                var detailText = document.querySelector(".detail-text")
                let swiper =document.querySelector(".swiper-container")
                let grading = document.querySelector(".grading")//结束页等级
                var information =[ "渣渣青铜怕过谁，音乐一响就胡怼！这位盆友，没事多听听酷狗音乐吧！传说中的音乐黑洞就素你啦!",
                "萌萌哒白银新手！我们知道你已经尽力了！晒晒结果吧，说不定可以萌到个对象呢~",
                "失敬失敬！十二星座黄金“音”斗士，你是哪一宫？向你的基友们寄送挑战书吧！",
                "说，你是不是隐匿多年的酷狗会员？对音乐的涉猎有点广泛啊！快晒出段位，接受世人的瞻仰吧！",
                "是天性压抑了太久，还是一个人寂寞到癫狂？我们的题库都不够你做了啊！行走的中华小曲库，快晒结果独孤求败吧！"]
                clearInterval(timer1);
                questionAnswer.style.display = "none"
                swiper.style.display ="none"
                first.style.width = "300vw"
               
                grading.classList.add("down");
                resetButton.classList.add("left")
                shareButton.classList.add("right")

                var grade = parseInt(sorce / 6);
                if (grade >= 5) grade = 4;
                detailText.innerText = information[grade];
                guess.innerText = `猜中${sorce}首`
                gradingImag.src = `./images/grade${grade}.png`
                audio.pause();
            }

            else {
                timeText = document.querySelector(".questionAnswer .mouseTime .timeText ")
                error = Math.ceil(error / 1000)
                timeText.innerText = `${error}s`
                //console.log(error);

            }
        }, 1000);
    }
}
//再来一次
resetButton.addEventListener("click",function(){
    let first = document.querySelector(".first");
    let questionAnswer = document.querySelector(".questionAnswer");
    let swiper =document.querySelector(".swiper-container")
    let grading = document.querySelector(".grading")//结束页等级

    grading.classList.remove("down");
    resetButton.classList.remove("left")
    shareButton.classList.remove("right")
    questionAnswer.style.display = "block"
    swiper.style.display ="block"
    first.style.width = "400vw"
    questionNum = 0;//当前问题数
    sorce = 0;
    timeText = document.querySelector(".questionAnswer .mouseTime .timeText ")
    timeText.innerText = `60s`
    doing();
   
})





/*预加载*/
//获取30首歌地址随机
let loadSuccess = true;
$ajax({ url: "json/music.json" }).then((res) => {
    musicData = res.sort(() => {
        return (Math.random() - 0.5)
    }).slice(0, 30)
    text = document.querySelectorAll(".questionAnswer ul li .text")
    console.log(musicData);
    for (let i = 0; i < text.length; i++) {
        text[i].innerText = `${musicData[questionNum].item[i]}`
    }
    let musicSong = musicData.map((e) => e.audio)
    return musicSong
})
    .then((res) => {
        //  console.log(res);
        let preload = new createjs.LoadQueue(true);
        //注意加载音频文件需要调用如下代码行
        preload.installPlugin(createjs.SOUND);
        //为preload添加当前队列变化时展示的进度事件
        preload.addEventListener("progress", handleFileProgress);
        //为preloaded添加当队列完成全部加载后触发事件
        preload.addEventListener("complete", loadComplete);
        preload.addEventListener("error", loadErr);
        //设置最大并发连接数  最大值为10
        preload.setMaxConnections(10);
        preload.loadManifest(res);

        //进度显示
        function handleFileProgress(event) {
            let progressNow = document.querySelector(".progressNow .text span")
            if (loadSuccess) {
                progressNow.innerText = `${(event.loaded * 100).toFixed(2)}%`
            }
        }
        //完成时的操作
        function loadComplete() {
            if (!loadSuccess) return;
            let page = document.querySelector(".first")
            setTimeout(function () {
                page.style[`transform`] = "translate(-100vw)"
            }, 300)
        }
        function loadErr() {
            console.log("加载出错了gg");
            loadSuccess = false;
        }
    })

